package com.koron.gateway.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {

    public static final String API_URI = "/v2/api-docs";

    private final RouteLocator routeLocator;

    @Autowired
    private SwaggerProperties swaggerProperties;

    private final String version = "2.0";

    @Value("${spring.application.name}")
    private String self;

    @Autowired
    public SwaggerProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        if (!swaggerProperties.getEnableSwagger()) {
            return null;
        }
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routeHosts = new ArrayList<>();
        // 由于网关采用的是负载均衡的方式，因此我需要拿到所有应用的serviceId
        // 获取所有可用的host：serviceId
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
                //网关不用swagger
                .filter(route -> !self.equals(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        // 记录已经添加过的server，存在同一个应用注册了多个服务在nacos上
        Set<String> dealed = new HashSet<>();
        List<Map<String, String>> services = swaggerProperties.getServices();
        services.forEach(service -> {
            String groupName = service.get("groupName");
            String serviceId = service.get("serviceId");
            // 拼接url，样式为/serviceId/v2/api-info，当网关调用这个接口时，会自动通过负载均衡寻找对应的主机
            if (routeHosts.contains(serviceId) && !dealed.contains(serviceId)) {
                dealed.add(serviceId);
                resources.add(createResource(serviceId, serviceId, this.version, groupName));
            }
        });
        return resources;

    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    private SwaggerResource createResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/" + location + API_URI);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    private SwaggerResource createResource(String name, String location, String version, String groupName) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/" + location + API_URI + "?group=" + groupName);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    private Properties readProperties() {
        Properties p = new Properties();
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(SwaggerProvider.class.getResourceAsStream("/swagger.properties"), StandardCharsets.UTF_8);
            p.load(in);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("加载 swagger.properties 属性文件出错,错误信息:" + e.getMessage());
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return p;
    }

}
